package com.shark.open.config;

import com.shark.model.Constant;
import com.shark.model.SharkUtil;
import com.shark.model.erp.StationAccessConfModel;
import com.shark.open.cache.AccessConfCache;
import com.shark.utils.exception.XException;
import com.shark.utils.tools.ConditionTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
@Component
public class ContextInterceptor implements HandlerInterceptor, Constant {
    @Resource
    private AccessConfCache accessConfCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof ResourceHttpRequestHandler)
            return true;
        String accessId = Optional.ofNullable(request.getHeader("accessId")).orElseThrow(() -> new XException(40000, "accessId不能为空"));
        String timespan = Optional.ofNullable(request.getHeader("timespan")).orElseThrow(() -> new XException(40000, "timespan不能为空"));
        String sign = Optional.ofNullable(request.getHeader("sign")).orElseThrow(() -> new XException(40000, "sign不能为空"));
        StationAccessConfModel accessConf = accessConfCache.get(accessId);
        ConditionTool.checkNotNull(accessConf, "未注册的AccessId");
        ConditionTool.checkArgument(SharkUtil.gtZero(accessConf.getStatus()), "AccessId已禁用");
        ReqContext.setContext(ReqContext.AccessContext.of(accessConf).updateReq(timespan, sign));
        return true;
    }

}
